package com.example.mybatisplus.controller;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.example.mybatisplus.exception.AppException;
import com.example.mybatisplus.exception.AppExceptionCodeMsg;

import com.example.mybatisplus.pojo.Food;
import com.example.mybatisplus.query.BaseQuery;
import com.example.mybatisplus.vo.ResultBean;
import javafx.collections.ObservableArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


public class BaseController<T,W>{

	@Autowired
	IService<T> baseService;
	@PostMapping      //  请求方式 + 请求路径   post  /business
	public ResultBean save(@RequestBody T t) throws Exception {
		boolean update = baseService.saveOrUpdate(t);
		if(!update){
			//抛异常
			throw new AppException(AppExceptionCodeMsg.SAVE_FAIL);
		}
		return ResultBean.SUCCESS();
	}

	@DeleteMapping("/{id}")
	public ResultBean delete(@PathVariable("id") Integer id) throws Exception {
		boolean remove = baseService.removeById(id);
		if(!remove){
			//抛异常
			throw new AppException(AppExceptionCodeMsg.DELETE_FAIL);
		}
		return ResultBean.SUCCESS();
	}
	@GetMapping("/{id}")
	public ResultBean getById (@PathVariable("id") Integer id) throws Exception {
		T t =(T) baseService.getById(id);
		if(t == null){
			throw new AppException(AppExceptionCodeMsg.DATA_NOT_FOUND);
		}
		return ResultBean.SUCCESS(t);
	}
	@PostMapping("/all")
	public <W extends BaseQuery> ResultBean getAll (@RequestBody W baseQuery) throws Exception {
		System.out.println("-------BaseController-----getAll--------");
		IPage<T> page = new Page<>(baseQuery.getPageNow(),baseQuery.getPageCount());
		List<T> list = baseService.list(page, baseQuery.getQueryWrapper());
		//这里只带了一个参数
		page.setRecords(list);
		return ResultBean.SUCCESS(page);
	}
	@GetMapping("/batch")
	public ResultBean getBatchDel(@RequestBody List<Integer> list) throws Exception {
		//因为在前端的时候，直接变成19，21的形式了，在后端只需要进行转换即可
		boolean flg=baseService.removeByIds(list);
		if(!flg){
			throw new AppException(AppExceptionCodeMsg.SAVE_FAIL);
		}
		return ResultBean.SUCCESS();
	}
}
